﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ERP_RORZE_DLL.Product.DAO;
using ERP_RORZE_DLL.Product.database;
using ERP_RORZE_PERMISSION.Base;
using ERP_RORZE_SYSTEM;
using BaseDAO = ERP_RORZE_TOOL.DBAccess.BaseDAO;
using Utilities = ERP_RORZE_TOOL.Common.Utilities;

namespace ERP_RORZE_PRODUCT.Product.MO
{
    public partial class frm_MONGCheckEdit : DevExpress.XtraEditors.XtraForm
    {
        INISettings mySetting = new INISettings();
        private SqlConnection myConnection;
        ClsMODAO clsMODAO = new ClsMODAO();
        DataTable dt;
        DataTable dtMoNo;
        ClsPartDataDAO clspartDAO = new ClsPartDataDAO();
        public event EventHandler Reload;
        AutoCompleteStringCollection itemMoNo = new AutoCompleteStringCollection();

        private LogUtils log;
        public string ID;
        public string Date;
        public string MONo;
        public string StaffID;
        public string OptionID;
        public string justment;
        public string Qty;
        public string Note;
        public string Finished;
        public frm_MONGCheckEdit()
        {
            InitializeComponent();
            myConnection = new SqlConnection(mySetting.SQLConnectionString);
            cbMONo.LostFocus += cbMONo_LostFocus;
            log = new LogUtils();
        }

        private bool IsFocus()
        {
            if ((ActiveControl is TextBox || ActiveControl is System.Windows.Forms.ComboBox ||
                 ActiveControl is System.Windows.Forms.DateTimePicker))
                return true;
            else
                return false;
        }

        void cbMONo_LostFocus(object sender, EventArgs e)
        {
            if (cbMONo.Items.Count <= 0 && !cbMONo.Text.Trim().Equals(string.Empty) && IsFocus())
            {
                dtMoNo = BaseDAO.ExecuteQuery("Select * from [242_MO] where MONo='" + cbMONo.Text + "'");
                if (dtMoNo.Rows.Count <= 0)
                {
                    dateDate.Focus();
                    MessageBox.Show("Không có đơn hàng này.");
                    return;
                }
                else if (dtMoNo.Rows.Count > 1)
                {
                    dateDate.Focus();
                    MessageBox.Show("Có hai đơn hàng này trong bảng MO List???");
                    return;
                }
                else
                {
                    cbMONo.Text = dtMoNo.Rows[0]["MONo"].ToString();
                    txtPartNo.Text = dtMoNo.Rows[0]["PartID"].ToString();
                    txtMOQty.Text = dtMoNo.Rows[0]["MOQty"].ToString();
                    checkFinish.Checked = (bool)dtMoNo.Rows[0]["Finished"];
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (checkFinish.Checked == true)
            {
                MessageBox.Show("MO đã hoàn thành. Hãy xem lại");
            }
            else if (cbJustMent.Text == "")
            {
                MessageBox.Show("Chưa chọn JustMent");
            }
            else if (txtQuantity.Text == "")
            {
                MessageBox.Show("Chưa nhập Quantity");
            }
            else if (GetData())
            {
                try
                {
                    ClsNGCheckTable b = new ClsNGCheckTable();
                    b.ID = int.Parse(ID);
                    b.MONo = cbMONo.Text;
                    b.Date = dateDate.Value;
                    b.StaffID = cbStaffID.Text;
                    b.OptionID = cbOptionID.Text;
                    b.Justment = cbJustMent.Text;
                    b.Note = txtNote.Text;
                    b.Qty = int.Parse(txtQuantity.Text);

                    clsMODAO.UpdateNGCheck(b);

                    //write Log
                    log.Table = LogConstant.Table.Product.MONGCheckDetail;
                    log.Task = LogConstant.Task.Update;
                    log.Description = "MONo: " + b.MONo + "; OptionID: " + b.OptionID + "; Date: " + b.Date + " where ID: " + b.ID;
                    log.WriteLog();

                    if (b.Justment.Equals("NG"))
                    {
                        int ngQty =
                            (int)(BaseDAO.ExecuteScalar("Select SUM([242_NGCheck].Qty) from [242_NGCheck] WHERE MONo ='" + b.MONo + "' and [justment] = 'NG'"));
                        MessageBox.Show("Đã nhập xong. \nSố lượng NG hiện tại là: " + ngQty.ToString());
                        cbMONo.Focus();
                    }
                    else
                    {
                        MessageBox.Show("Đã nhập xong");
                        cbMONo.Focus();
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void frm_MONGCheckEdit_Load(object sender, EventArgs e)
        {
            //dt = clsMODAO.GetAllMO();
            //List<ClsMOTable> objs = new List<ClsMOTable>();
            //foreach (DataRow r in dt.Rows)
            //{
            //    ClsMOTable obj = new ClsMOTable();
            //    obj.MONo = r["MONo"].ToString();  //
            //    obj.MOQty = int.Parse(r["MOQty"].ToString());////
            //    obj.Finished = (r["Finished"].ToString()==string.Empty) ? false : (bool)r["Finished"];  ////
            //    //MessageBox.Show(objs.ToString());
            //    objs.Add(obj);
            //}
            //cbMONo.DataSource = objs;
            //cbMONo.DisplayMember = "MONo";
            //cbMONo.ValueMember = "MONo";

            BindDataMoNo();

            //GetAll StaffID
            dt = clsMODAO.GetAllStaffID();
            cbStaffID.DataSource = dt;
            cbStaffID.DisplayMember = "StaffID";
            cbStaffID.ValueMember = "StaffID";

            // lấy OptionID
            dt = clspartDAO.GetAllOptionID();
            cbOptionID.DataSource = dt;
            cbOptionID.DisplayMember = "OptionID";
            cbOptionID.ValueMember = "OptionID";

            dateDate.Value = DateTime.Parse(Date);
            cbMONo.SelectedValue = MONo;
            cbStaffID.SelectedValue = StaffID;
            cbOptionID.SelectedValue = OptionID;
            cbJustMent.SelectedText = justment;

            txtQuantity.Text = Qty;
            txtNote.Text = Note;
            //checkFinish.Checked = bool.Parse(Finished);
        }

        private void cbMONo_SelectedIndexChanged(object sender, EventArgs e)
        {
            ClsMOTable obj = ((ClsMOTable)cbMONo.SelectedItem);
            checkFinish.Checked = obj.Finished;
            txtMOQty.Text = obj.MOQty.ToString();

            ClsMOOptionTable c = new ClsMOOptionTable();
            c.MONo = cbMONo.Text;
            //GetAll OptionID
            dt = clsMODAO.GetAllOptionID(c);
            cbOptionID.DataSource = dt;
            cbOptionID.DisplayMember = "OptionID";
            cbOptionID.ValueMember = "OptionID";

            //Get All MONo
            //dt = clsMODAO.GetAllMO();
        }

        protected override bool ProcessKeyPreview(ref Message m)
        {
            if (m.Msg == 0x0100 && (int)m.WParam == 13)
            {
                this.ProcessTabKey(true);
            }
            return base.ProcessKeyPreview(ref m);
        }

        private void BindDataMoNo()
        {
            myConnection.Open();
            SqlCommand cmd_sql = myConnection.CreateCommand();
            cmd_sql.CommandText = "SELECT [242_MO].PartID, [242_MO].MOQty, [242_MO].MONo FROM [242_MO]";
            SqlDataReader dataReader = cmd_sql.ExecuteReader();
            while (dataReader.Read())
            {
                itemMoNo.Add(dataReader["MONo"].ToString());
            }
            dataReader.Close();
            cmd_sql.Dispose();
            myConnection.Close();

            //dtMoNo = BaseDAO.ExecuteQuery("SELECT [242_MO].MONo, [242_MO].PartID FROM [242_MO] where [242_MO].[date] >  DATEADD(mm,-2,getdate())");
            cbMONo.AutoCompleteCustomSource = itemMoNo;
            cbMONo.Text = MONo;

            dtMoNo = BaseDAO.ExecuteQuery("Select * from [242_MO] where MONo='" + cbMONo.Text + "'");
            checkFinish.Checked = (dtMoNo.Rows[0]["Finished"].ToString() == string.Empty) ? false : (bool)dtMoNo.Rows[0]["Finished"];
            txtPartNo.Text = dtMoNo.Rows[0]["PartID"].ToString();
            txtMOQty.Text = dtMoNo.Rows[0]["MOQty"].ToString();
        }

        private bool GetData()
        {
            dtMoNo = BaseDAO.ExecuteQuery("Select * from [242_MO] where MONo='" + cbMONo.Text + "'");
            if (dtMoNo.Rows.Count <= 0)
            {
                dateDate.Focus();
                MessageBox.Show("Không có đơn hàng này.");
                return false;
            }

            if (dtMoNo.Rows.Count > 1)
            {
                dateDate.Focus();
                MessageBox.Show("Có hai đơn hàng này trong bảng MO List???");
                return false;
            }

            if (!Utilities.IsNumericInt(txtQuantity.Text))
            {
                MessageBox.Show("Số lượng phải là số nguyên.");
                return false;
            }

            if (int.Parse(txtQuantity.Text) < 0)
            {
                MessageBox.Show("Số lượng phải lớn hơn 0.");
                return false;
            }

            if (float.Parse(txtQuantity.Text) > float.Parse(txtMOQty.Text))
            {
                MessageBox.Show("Số lượng không được lớn hơn số lượng lệnh.");
                return false;
            }


            //DataTable dtIntNg = BaseDAO.ExecuteQuery("SELECT          [242_NGCheck].MONo, SUM([242_NGCheck].Qty) AS QtyOfSum, " +
            //                          "                        [242_NGCheck].Justment " +
            //                          "  FROM            [242_MO] INNER JOIN " +
            //                          "                        [242_NGCheck] ON [242_MO].MONo = [242_NGCheck].MONo " +
            //                          "  WHERE           ([242_NGCheck].Justment = 'NG') and [242_NGCheck].MONo = '" + cbMONo.Text + "'" +
            //                          "  GROUP BY     [242_NGCheck].MONo, [242_NGCheck].Justment " +
            //                          "  HAVING        (SUM([242_NGCheck].Qty) > 0)");
            //DataTable dtSoDu = BaseDAO.ExecuteQuery("SELECT     MONo, MOQty, Qty, MOQty - Qty AS SoDu " +
            //                                         "       FROM         [242_BusOder] " +
            //                                         "       WHERE     (MONo IS NOT NULL) and MONo='" + cbMONo.Text + "'");
            //if (dtIntNg.Rows.Count > 0)
            //{
            //    intNg = (Utilities.IsNullOrEmpty(dtIntNg.Rows[0]["QtyOfSum"].ToString()))
            //                 ? 0
            //                 : int.Parse(dtIntNg.Rows[0]["QtyOfSum"].ToString());
            //}

            //if (dtSoDu.Rows.Count > 0)
            //{
            //    soDu = (Utilities.IsNullOrEmpty(dtSoDu.Rows[0]["SoDu"].ToString()))
            //               ? 0
            //               : int.Parse(dtSoDu.Rows[0]["SoDu"].ToString());
            //}

            //if (((int.Parse(txtQuantity.Text) + intNg) > soDu) && cbJustMent.Text.Equals("NG"))
            //{
            //    MessageBox.Show("Cho đến thời điểm hiện tại số lượng NG là: " + intNg.ToString() + " sản phẩm. \nSố lượng sản phẩm dư cho lệnh này " + soDu.ToString() + " sản phẩm thôi.\nKiểm tra lại số lượng!");
            //    return false;
            //}

            return true;
        }

        private void frm_MONGCheckEdit_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Alt)
            {
                if (e.KeyCode == Keys.D)
                {
                    this.btnEdit.PerformClick();
                }
            }
            else if (e.KeyCode == Keys.End)
            {
                btnEdit.Focus();
            }
            else if (e.KeyCode == Keys.Home)
            {
                dateDate.Focus();
            }
        }

    }
}